package com.blog.Utils;

import com.blog.base.Constans;
import com.blog.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.bcel.Const;
import org.elasticsearch.common.recycler.Recycler;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author 任浩
 * @version 1.0
 */

@Slf4j
public final class CookieUtils {
    /**
     * 设置Cookie的值 不设置生效时间默认浏览器关闭即失效,也不编码
     */


    /**
     * 普通的设置cookie值，没有设置有效时间和编码
     * @param response
     * @param name
     * @param value
     */
    public static void setCookie(HttpServletResponse response, String name,
                                 String value) {
        realRetCookie(response,name,value,0,false);
    }


    /**
     *  设置Cookie。
     * @param response
     * @param name
     * @param value
     * @param maxAge  //cookie的有效时间
     * @param isEncode  //是否进行编码
     */
    public static void setCookie(HttpServletResponse response, String name,
                                 String value,int maxAge,boolean isEncode)
    {
        realRetCookie(response, name, value,  maxAge,isEncode);
    }


    /**
     * 真正设置cookie的方法
     * @param response
     * @param name
     * @param value
     * @param maxAge
     * @param isEncode
     * @return
     */
    private static void realRetCookie(HttpServletResponse response, String name,
                              String value,int maxAge,boolean isEncode){
        try {
            if(value == null){
                value = "";
            }
            else if(isEncode){
                value = URLEncoder.encode(value,"utf-8");  //对值进行编码
            }
            Cookie cookie = new Cookie(name,value);
            if(maxAge > 0){
                cookie.setMaxAge(maxAge);
            }

            //可以设置cookie的域名，

            /**
             * 当你为cookie设置setPath("/")时，你告诉浏览器这个cookie对于该域名下的所有请求都是可见的
             * 也就是浏览器都会自动在请求头中包含这个cookie
             */
            cookie.setPath("/");
            response.addCookie(cookie);
        }
        catch (Exception e){
            e.printStackTrace();
            throw new ServiceException("设置cookie出错" + e.getMessage());
        }
    }


    /**
     * 得到存放在cookie中的用户token和用户id
     */
    public static Map<String,String> getCookieMessage(HttpServletRequest request){
//        AtomicReference<String> accessToken = null;
//        AtomicReference<String> userId = null;
        Cookie[] cookies = request.getCookies();
        if(null == cookies){
            log.info("cookies为null");
            throw new ServiceException(302,"cookie为null");
        }
        log.info("cookies的值为：{}",cookies.length);

//        if(cookies != null){
//            Arrays.stream(cookies).forEach(cookie -> {
//                if(Constans.Cookie_Token.equals(cookie.getName())){
//                    accessToken.set(cookie.getValue());
//                }
//                else if(Constans.Cookie_User.equals(cookie.getName())){
//                    userId.set(cookie.getValue());
//                }
//            });
//        }

        String tokenValue = null;
        String userIdValue = null;

        for (Cookie cookie : cookies) {
            if(Constans.Cookie_Token.equals(cookie.getName())){
                tokenValue = cookie.getValue();
            }
            else if(Constans.Cookie_User.equals(cookie.getName())){
                userIdValue = cookie.getValue();
            }
        }


//        String tokenValue = accessToken.get();
//        String userIdValue = userId.get();

        log.info("请求拿到的token为：" + tokenValue);
        log.info("请求拿到的id为：" + userIdValue);

        Map map = new HashMap();
        map.put(Constans.Cookie_Token,tokenValue);
        map.put(Constans.Cookie_User,userIdValue);

        return map;
    }

    /**
     * 清除cookie值
     * @param response
     */
    public static void removeCookie(HttpServletResponse response){
        Cookie cookie = new Cookie(Constans.Cookie_Token,"");
        cookie.setMaxAge(0); //立马过期
        cookie.setPath("/"); //设置有效路径.
        response.addCookie(cookie);

        Cookie cookie1 = new Cookie(Constans.Cookie_User,"");
        cookie1.setPath("/");
        cookie1.setMaxAge(0);
        response.addCookie(cookie1);
    }

}
